package api

import (
	"encoding/json"
	"net/http"
	"strconv"

	"rt.com/mocktool/mock"

	"rt.com/mocktool/values"
)

// setServerPort 设置服务端口号
func setServerPort(w http.ResponseWriter, r *http.Request) {
	debugAPI(w, r)
	urlParams := r.URL.Query()
	typeParam := urlParams.Get("type")
	portParam := urlParams.Get("port")
	globalInactiveParam := urlParams.Get("globalInactive")
	if typeParam == "" || portParam == "" || globalInactiveParam == "" {
		errResp, _ := json.Marshal(ErrorMsg{
			Msg:  values.ErrorWrongParams,
			Code: 100,
		})
		w.Write(errResp)
	}
	typeInt, err := strconv.Atoi(typeParam)
	if err != nil || typeInt < 0 || typeInt > 1 {
		errResp, _ := json.Marshal(ErrorMsg{
			Msg:  values.ErrorWrongParams,
			Code: 100,
		})
		w.Write(errResp)
	}
	portInt, err := strconv.Atoi(portParam)
	if err != nil || portInt < 0 || portInt > 65535 {
		errResp, _ := json.Marshal(ErrorMsg{
			Msg:  values.ErrorWrongParams,
			Code: 100,
		})
		w.Write(errResp)
	}
	globalInactiveInt, err := strconv.Atoi(globalInactiveParam)
	if err != nil {
		errResp, _ := json.Marshal(ErrorMsg{
			Msg:  values.ErrorWrongParams,
			Code: 100,
		})
		w.Write(errResp)
	}

	if typeInt == 0 {
		// 后台端口号变更
		mock.Instance.GetConfig().AdminPort = portInt
		mock.Instance.UploadConfig()
	} else if typeInt == 1 {
		// 代理端口号变更
		mock.Instance.GetConfig().ProxyPort = portInt
		mock.Instance.UploadConfig()
	} else if typeInt == 2 {
		// 全局拦截状态改变
		mock.Instance.GetConfig().GlobalInactive = globalInactiveInt
		mock.Instance.UploadConfig()
	}
	// 响应成功
	successResp, _ := json.Marshal(ErrorMsg{
		Msg:  "success",
		Code: 0,
	})
	// 写响应
	w.Write(successResp)
}
